package com.qf.controller;

import com.qf.service.AuthService;
import com.qf.util.CookieUtil;
import com.qf.util.JwtUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.util.UUID;

/**
 * @author 千锋健哥
 */
@RestController
@RequestMapping("/auth")
public class AuthController {

    @Autowired
    private AuthService authService;

    @Autowired
    private HttpServletResponse response;

    /**
     * 登录认证
     * @param userName
     * @param password
     * @return
     */
    @PostMapping("/login")
    public String login(String userName, String password) {
        if (StringUtils.isEmpty(userName) || StringUtils.isEmpty(password)) {
            return "用户名和密码不能为空!";
        }
        //认证
        boolean flag = authService.login(userName, password);
        if (flag) {
            //用户名密码正确, 生成jwt, 放入cookie, 并返回
            String jwt = JwtUtil.createJWT(UUID.randomUUID().toString(), userName, null);

            //jwt放入cookie中保存
            CookieUtil.addCookie(response, "localhost", "/", "token", jwt, -1, false);
            return jwt;
        }
        return  "用户名或者密码错误!";
    }
}
